﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Nova_DAL;
using Nova_Common;
using System.Data.Common;
using System.Data;
using System.Collections;
using System.Text;
using System.Drawing;
using Nova_Common.Extend;
using Nova_MOD;
using Nova_BLL;
using System.Reflection;

public partial class Storage_CheckBook : System.Web.UI.Page
{
    DbHelper access = new DbHelper();
    TCommandBll CmdBll = new TCommandBll();
    DbCommand cmd = null;
    string strSQL = "";
    static DataSet ds = null;

    //用于双伸位前后货位的标记
    string FrontPos_ID = "";//用于标记上一行的货位号
    Color Samecolor = Color.AliceBlue;//两个切换的颜色
    Color Diffcolor = Color.LightSkyBlue;

    //20210426 NF项目 双伸位巷道集合 需要结合项目双伸位巷道修改
    string[] ExtensionLanelists = new string[] { "01" };
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //BindddlLane_ID();
            BindGrid();
        }
    }

    private void BindddlLane_ID()
    {
        strSQL = @"SELECT distinct TBP.No_Lane  FROM TBase_Position TBP LEFT JOIN TBase_Zone TBZ ON TBP.Zone_ID = TBZ.Zone_ID WHERE TBZ.Structure=1";
        cmd = access.GetSqlStringCommond(strSQL);
        ddlLane_ID.DataTextField = "No_Lane";
        ddlLane_ID.DataValueField = "No_Lane";
        ddlLane_ID.DataSource = access.ExecuteDataSet(cmd);
        ddlLane_ID.DataBind();

        // ddlLane_ID.Items.Insert(0, new ListItem("请选择巷道号...", "0"));

    }



    private void BindGrid()
    {
        strSQL = @"select TBP.Pos_ID,TBT.Tray_ID,TBI.Mat_Code,TM.MAT_NAME,TBS.Mat_Num,TM.S01,TM.TM01,TM.S02,TM.TM03,TM.UNIT_BASE,TBS.PID,TBZ.Structure
                    from TBase_Storage TBS 
                    LEFT JOIN TBase_Interface TBI on TBI.Sec_Mat_ID = TBS.Sec_Mat_ID
                    LEFT JOIN TRel_TrayPosContainer TRT ON TRT.ContainerID = TBS.ContainerID
                    LEFT JOIN TBase_TrayPos TBT ON TBT.Relations_ID = TRT.Relations_ID
                    LEFT JOIN TRelations TRP ON TRP.Tray_ID = TBT.Tray_ID
                    LEFT JOIN TBase_Position TBP on TBP.Pos_ID = TRP.Pos_ID 
					LEFT JOIN TBase_Material AS TM ON TM.Mat_Code=TBI.Mat_Code
                    LEFT JOIN TBase_Zone TBZ ON TBP.Zone_ID = TBZ.Zone_ID
                    where 1=1 and TRP.Pos_ID !='200000000000' and  TBP.Pos_State=1 ";

        if (!string.IsNullOrEmpty(txt_Mat_Code.Text))
        {
            strSQL += @" and TBI.Mat_Code='" + txt_Mat_Code.Text.Trim() + "'";
        }
        if (!string.IsNullOrEmpty(txt_TrayID.Text))
        {
            strSQL += @" and TRP.Tray_ID like '%" + txt_TrayID.Text.Trim() + "'";
        }
        if(!string.IsNullOrEmpty(txt_Mat_Name.Text))
        {
            strSQL += @" and TM.MAT_NAME ='" + txt_Mat_Name.Text.Trim() + "'";
        }

        //if (!string.IsNullOrEmpty(txtPosID.Text))
        //{
        //    strSQL += @" and TBP.Pos_ID='" + txtPosID.Text.Trim() + "'";
        //}
        if (Position1.No_Lane != "0" && Position1.No_Lane != "")
        {
            strSQL += " AND TBP.No_Lane = '" + Position1.No_Lane.ToString() + "'";
        }
        if (Position1.No_Line != "0" && Position1.No_Line != "")
        {
            strSQL += " AND TBP.No_Line = '" + Position1.No_Line.ToString() + "'";
        }

        if (Position1.No_Col != "0" && Position1.No_Col != "")
        {
            strSQL += " AND TBP.No_Col = '" + Position1.No_Col.ToString() + "'";
        }
        if (Position1.No_Layer != "0" && Position1.No_Layer != "")
        {
            strSQL += " AND TBP.No_Layer = '" + Position1.No_Layer.ToString() + "'";
        }

        if (ddlLane_ID.SelectedIndex > 0)
        {
            strSQL += @" and TBP.No_Lane='" + ddlLane_ID.SelectedValue.ToString() + "'";
        }

        strSQL += " order by TBP.Pos_ID";

        cmd = access.GetSqlStringCommond(strSQL);
        DataTable dt = access.ExecuteDataTable(cmd);
        dt = dt.Rows.Count > 0 ? GetGvTable(dt) : dt;
        gv.DataSource = dt;
        gv.DataBind();
    }

    private DataTable GetGvTable(DataTable dt)
    {
        List<CheckStorageModel> newList = new List<CheckStorageModel>();
        List<CheckStorageModel> list = TableList.DataTableToList<CheckStorageModel>(dt);
        string allCountSub = string.Empty;
        foreach (var model in list)
        {
            if (newList.Exists(x => x.Tray_ID == model.Tray_ID))
            {
                CheckStorageModel storageModel = newList.Find(x => x.Tray_ID == model.Tray_ID);
                //storageModel.MAT_NAME = storageModel.MAT_NAME  + "/" + model.MAT_NAME;
                string info = string.Empty;
                if (!string.IsNullOrWhiteSpace(model.S01))
                {
                    info += string.Format("/{0}", model.S01);
                }
                if (!string.IsNullOrWhiteSpace(model.TM01))
                {
                    info += string.Format("/{0}", model.TM01);
                }
                if (!string.IsNullOrEmpty(model.TM03))
                {
                    info += string.Format("/{0}", model.TM03);
                }
                if (!string.IsNullOrEmpty(model.S02))
                {
                    info += string.Format("/{0}", model.S02);
                }
                storageModel.MAT_NAME = string.Format("{0}，{1}{2}/{3}", storageModel.MAT_NAME, model.MAT_NAME, info, model.Mat_Num);
            }
            else
            {
                string info = string.Empty;
                if (!string.IsNullOrWhiteSpace(model.S01))
                {
                    info += string.Format("/{0}", model.S01);
                }
                if (!string.IsNullOrWhiteSpace(model.TM01))
                {
                    info += string.Format("/{0}", model.TM01);
                }
                if (!string.IsNullOrEmpty(model.TM03))
                {
                    info += string.Format("/{0}", model.TM03);
                }
                if (!string.IsNullOrEmpty(model.S02))
                {
                    info += string.Format("/{0}", model.S02);
                }
                model.MAT_NAME = string.Format("{0}{1}/{2}", model.MAT_NAME, info, model.Mat_Num);
                newList.Add(model);
            }
        }

        return TableList.ListToDataTable(newList);
    }

    protected void ibnSearch_Click(object sender, ImageClickEventArgs e)
    {
        //Label1.Text = "";

        ////输入的货位号，是否是数据类型的判断
        //if (!string.IsNullOrEmpty(txtPosID.Text))
        //{
        //    long data = 0;
        //    bool flag = long.TryParse(txtPosID.Text.Trim(), out data);

        //    if (!flag)
        //    {
        //        Label1.Text = "货位号不是有效值！";

        //        return;
        //    }


        //}

        BindGrid();

    }
    protected void ibtnJoinCommand_Click(object sender, ImageClickEventArgs e)
    {
        Label1.Text = "";
        int count = 0;

        int SucessNum = 0;
        int FailNum = 0;
        string Infor = "";

        try
        {

            #region xgw 20200707 add 1、 双伸位巷道（2#巷道） 后面的货位（偶数层）添加能否出库的业务逻辑判断，不满足条件提示，跳出；   
            //// 后面的货位判断： 如果前面的货位没有选中，则都要判断前面的货位状态
            //for (int k = 0; k < this.gv.Rows.Count; k++)
            //{
            //    CheckBox chkSelect = (CheckBox)gv.Rows[k].Cells[0].FindControl("chkSelect");
            //    if (chkSelect.Checked)
            //    {
            //        string Pos_Id = this.gv.Rows[k].Cells[2].Text.ToString();
            //        bool SeleFront = false; //是否选择了前面货位
            //        if ((Convert.ToInt32(Pos_Id.Substring(8, 2)) % 2) == 0 && Pos_Id.Substring(2, 2) == "02")// 双伸位 后面的货位
            //        {

            //            if (k > 0)
            //            {
            //                if (((Convert.ToInt64(Pos_Id.Substring(0, 10)) - 1) * 100) == Convert.ToInt64(this.gv.Rows[k - 1].Cells[2].Text.ToString()))
            //                {
            //                    CheckBox chkSelect1 = (CheckBox)gv.Rows[k - 1].Cells[0].FindControl("chkSelect");
            //                    if (chkSelect1.Checked)
            //                    {
            //                        SeleFront = true;
            //                    }
            //                }


            //            }

            //            if (!SeleFront)
            //            {
            //                long Pos_ID_Front = (Convert.ToInt64(Pos_Id.Substring(0, 10)) - 1) * 100;
            //                string str1 = string.Format(@"select * from  dbo.TBase_Position where Pos_ID={0}
            //        ", Pos_ID_Front);

            //                cmd = access.GetSqlStringCommond(str1);
            //                ds = access.ExecuteDataSet(cmd);
            //                if (ds.Tables[0].Rows.Count > 0)
            //                {
            //                    if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 2)
            //                    {
            //                        this.Label1.Text = Pos_Id + "前面的货位有入库预定，此货位的货物不能盘点出库！";
            //                        return;
            //                    }

            //                    if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 1)
            //                    {
            //                        this.Label1.Text = Pos_Id + "前面的货位为有货状态，" + Pos_ID_Front.ToString() + "货位的货必须先选择盘点出库， 此货位的货物才能盘点出库！";
            //                        return;
            //                    }

            //                    if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 6)
            //                    {
            //                        this.Label1.Text = Pos_Id + "前面的货位有移库预定，此货位的货物不能盘点出库！";
            //                        return;
            //                    }


            //                }
            //            }

            //        }

            //    }
            //}
            #endregion

            #region xgw 20210506 add 1、 双伸位巷道 后面的货位（偶数层）添加能否出库的业务逻辑判断(如果前面货位状态为入库移库预定)，不满足条件提示，跳出；   
            //for (int k = 0; k < this.gv.Rows.Count; k++)
            //{
            //    CheckBox chkSelect = (CheckBox)gv.Rows[k].Cells[0].FindControl("chkSelect");
            //    if (chkSelect.Checked)
            //    {
            //        string Pos_Id = this.gv.Rows[k].Cells[2].Text.ToString();
            //        if ((Convert.ToInt32(Pos_Id.Substring(8, 2)) % 2) == 0 && ExtensionLanelists.Contains(Pos_Id.Substring(2, 2)))// 双伸位 后面的货位
            //        {

            //            long Pos_ID_Front = (Convert.ToInt64(Pos_Id.Substring(0, 10)) - 1) * 100;
            //            string str1 = string.Format(@"select * from  TBase_Position where Pos_ID={0}", Pos_ID_Front);

            //            cmd = access.GetSqlStringCommond(str1);
            //            ds = access.ExecuteDataSet(cmd);
            //            if (ds.Tables[0].Rows.Count > 0)
            //            {
            //                if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 2)
            //                {
            //                    this.Label1.Text = Pos_Id + "前面的货位有入库预定，此货位的货物不能出库！";
            //                    return;
            //                }


            //                if (Convert.ToInt16(ds.Tables[0].Rows[0]["Pos_State"]) == 6)
            //                {
            //                    this.Label1.Text = Pos_Id + "前面的货位有移库预定，此货位的货物不能出库！";
            //                    return;
            //                }

            //            }


            //        }
            //    }

            //}
            #endregion

            // 获取出库口设备编号(出库只能往1004口出)
            int sqid = 1004;
            if (!CmdBll.IsDeviceEnable(sqid))
            {
                Label1.Text = "出库路径输送线设备、巷道处于禁用或者离线模式!";
                //ShowBox.MessageBox(this.Page, "出库口设备现在处于禁用或者离线模式,无法下发指令!");
                return;
            }

            for (int i = 0; i < gv.Rows.Count; i++)
            {
                CheckBox chkSelect = (CheckBox)gv.Rows[i].Cells[0].FindControl("chkSelect");
                if (chkSelect.Checked)
                {
                    count += 1;
                    cmd = access.GetStoredProcCommond("dbo.SP_ASRS_Generate_PanDian_CMDS_ByPos_YMJX");
                    access.AddInParameter(cmd, "@PosS_ID", DbType.String, gv.Rows[i].Cells[2].Text.ToString());
                    access.AddInParameter(cmd, "@SQIDE", DbType.String, sqid);
                    access.AddInParameter(cmd, "@USERNAME", DbType.String, Request.Cookies["vNovaUserNo"].Value.ToString());
                    access.AddOutParameter(cmd, "@ResNO", DbType.Int16, 100);
                    access.AddOutParameter(cmd, "@RESMSG", DbType.String, 255);
                    access.ExecuteNonQuery(cmd);
                    int iResNo = Convert.ToInt32(access.GetParameter(cmd, "@ResNO").Value.ToString());
                    string strErrMsg = access.GetParameter(cmd, "@RESMSG").Value.ToString();

                    if (iResNo < 0) //失败
                    {
                        FailNum++;
                        Infor += strErrMsg + ";";
                    }
                    else
                    {
                        SucessNum++;
                    }
                }
            }
            if (count == 0)
            {
                Label1.Text = "请选择要盘点的托盘！";
                return;
            }

            Label1.Text = "成功执行：" + SucessNum + ";失败了:" + FailNum + ";" + Infor + "";
            //if (iResNo > 0)
            //{
            //    Label1.Text = "盘点指令下发成功！";
            //    //bind();
            //}
            //else
            //{
            //    Label1.Text = "盘点指令下发失败！";
            //}
            BindGrid();
        }
        catch (Exception ex)
        {
            Label1.Text = "盘点指令执行异常跳出！";
        }
    }
    protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gv.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    /// <summary>
    /// 增加双伸位前后货位 展示相同颜色标记 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView dr = (DataRowView)e.Row.DataItem;
            CheckBox cbx = (CheckBox)e.Row.FindControl("chkSelect");
            if (Convert.ToInt16(dr["Structure"]) != 1)
            {
                cbx.Visible = false;
            }
            else
            {
                cbx.Visible = true;
            }

            #region  增加双伸位前后货位 展示相同颜色标记 
            string Pos_Id = e.Row.Cells[2].Text.ToString();  //存储货位

            //第1巷道（双伸位） 后面货位（偶数层） 与前一行数据货位为前后关系  显示同样颜色， 否则显示不同颜色
            if ((Convert.ToInt32(Pos_Id.Substring(8, 2)) % 2) == 0 && ExtensionLanelists.Contains(Pos_Id.Substring(2, 2)) && ((Convert.ToInt64(Pos_Id.Substring(0, 10)) - 1) * 100)._ToString() == FrontPos_ID)
            {
               // e.Row.BackColor = Samecolor;

            }
            else
            {
               // e.Row.BackColor = Diffcolor;

               // Color Middlecolor = Samecolor;
               // Samecolor = Diffcolor;
               // Diffcolor = Middlecolor;

            }

            FrontPos_ID = Pos_Id;

            #endregion

        }
    }
    //protected void gv_PageIndexChanged(object sender, EventArgs e)
    //{

    //    BindGrid();
    //}
    protected void ibtn_Excel_Click(object sender, ImageClickEventArgs e)
    {
        DataTable dt = ds.Tables[0];
        Response.Clear();
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.Charset = "GB2312";
        Response.AppendHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode("盘点" + System.DateTime.Now.ToString("MM.dd") + ".xls"));
        Response.ContentType = "application/ms-excel";

        Response.Write("货位号\t托盘号\t物料编码\t物料名称\t物料数量\t");

        Response.Write(Environment.NewLine);
        foreach (DataRow dr in dt.Rows)
        {

            StringBuilder sb = new StringBuilder();

            sb.Append(("" + dr["Pos_ID"]) + "\t" + ("" + dr["Tray_ID"]) + "\t" + ("" + dr["Mat_Code"]) + "\t" + dr["Mat_Name"] + "\t" + dr["Mat_Num"] + "\t" + "  \t");

            Response.Write(sb.ToString());
            Response.Write(Environment.NewLine);


        }


        Response.End();
        // if (gv.Rows.Count==0)
        // {
        //     return;
        // }

        // //DataTable dtOut = ds.Tables[0];
        // Response.Clear();
        // Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        // Response.Charset = "GB2312";
        // Response.AppendHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode("盘点" + System.DateTime.Now.ToString("MM.dd") + ".xls"));
        // Response.ContentType = "application/ms-excel";

        //Response.Write("货位号\t 托盘号\t 物料编码 \t 物料名称\t 数量\t 实际数量\t");

        // Response.Write(Environment.NewLine);
        // for (int i = 0; i < gv.Rows.Count; i++)
        // {

        //     //CheckBox chk = (CheckBox)gv.Rows[i].FindControl("chkSelect");
        //     //if (chk.Checked)
        //     //{
        //         //DataRow[] drw = dtOut.Select("PID='" + gv.DataKeys[i].Value.ToString() + "'");
        //         StringBuilder sb = new StringBuilder();
        //         //for (int j = 0; j < dtOut.Columns.Count - 2; j++)
        //         //{
        //         //    sb.Append("" + dtOut.Rows[i][j].ToString());
        //         //    sb.Append("\t");
        //         //}
        //         sb.Append("" + gv.Rows[i].Cells[2].Text + "\t" + "" + gv.Rows[i].Cells[3].Text + "\t"+"" + gv.Rows[i].Cells[4].Text + "\t"
        //             + gv.Rows[i].Cells[5].Text + "\t" + gv.Rows[i].Cells[7].Text + "\t"+"  \t");
        //         Response.Write(sb.ToString());
        //         Response.Write(Environment.NewLine);
        //     //}

        // }

        // //DataTable dtOut = GetExcelData();

        // //for (int i = 0; i < dtOut.Rows.Count; i++)
        // //{
        // //    StringBuilder sb = new StringBuilder();
        // //    for (int j = 0; j < dtOut.Columns.Count - 2; j++)
        // //    {
        // //        sb.Append(""+dtOut.Rows[i][j].ToString());
        // //        sb.Append("\t");
        // //    }
        // //    Response.Write(sb.ToString());
        // //    Response.Write(Environment.NewLine);
        // //}
        // Response.End();
    }

    //public DataTable GetExcelData()
    //{
    //    DataTable dt = new DataTable();
    //    dt.Columns.Add("Pos_ID",typeof(string));
    //    dt.Columns.Add("Tray_ID", typeof(Int64));
    //    dt.Columns.Add("Mat_Code",typeof(string));
    //    dt.Columns.Add("MAT_NAME",typeof(string));
    //    dt.Columns.Add("Mat_Num",typeof(decimal));
    //    dt.Columns.Add("UNIT_BASE",typeof(string));
    //    dt.Columns.Add("PID",typeof(string));

    //    dt.Rows.Add(new object[]{"100110020100",1003,"30021","aaa",100,"个","1"});
    //    dt.Rows.Add(new object[] { "100210020100", 1004, "30022", "aaa1", 100, "个", "2" });
    //    dt.Rows.Add(new object[] { "100110040100", 1005, "30023", "aaa2", 100, "个", "3" });
    //    return dt;

    //}


    /// <summary>
    /// 重置
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReset_Click(object sender, ImageClickEventArgs e)
    {
        txt_Mat_Name.Text = "";
        txt_Mat_Code.Text = "";
        //txtPosID.Text = "";

        Position1.No_Lane = "0";
        Position1.No_Layer = "0";
        Position1.No_Line = "0";
        Position1.No_Col = "0";

        ddlSQIDE.SelectedIndex = 0;
        ddlLane_ID.SelectedIndex = 0;
        this.Label1.Text = "";
    }

}
